package com.getpebble.android.onboarding;

import android.content.SharedPreferences;
import com.getpebble.android.PebbleApplication;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.common.core.util.PblPreferences;
import com.getpebble.android.common.core.util.PblPreferences.PrefKey;
import com.getpebble.android.common.model.PblDevice;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class OnboardingPreferences {
    private static final String TAG = OnboardingPreferences.class.getSimpleName();
    private static Integer sApplicationOnboardingVersion = null;
    private static Map<String, Integer> sDeviceOnboardingVersion = new ConcurrentHashMap();

    public static void setOnboardingVersion(PblDevice device, int version) {
        if (device == null) {
            Trace.error(TAG, "*** Failed to set onboarding version, device is null");
            return;
        }
        sDeviceOnboardingVersion.put(device.getAddress(), Integer.valueOf(version));
        sApplicationOnboardingVersion = Integer.valueOf(version);
        Trace.info(TAG, String.format("Setting onboarding version %d for device %s", new Object[]{Integer.valueOf(version), device.getName()}));
        getInstance().edit().putInt(device.getAddress(), version).putInt("pref_key_app_onboarding_version", version).apply();
    }

    public static int getOnboardingVersionFromPreferences(PblDevice device) {
        if (device == null) {
            return -1;
        }
        if (sDeviceOnboardingVersion.containsKey(device.getAddress())) {
            return ((Integer) sDeviceOnboardingVersion.get(device.getAddress())).intValue();
        }
        return getInstance().getInt(device.getAddress(), -1);
    }

    public static int getApplicationOnboardingVersion() {
        if (sApplicationOnboardingVersion != null) {
            return sApplicationOnboardingVersion.intValue();
        }
        SharedPreferences sharedPreferences = getInstance();
        int version = sharedPreferences.getInt("pref_key_app_onboarding_version", -1);
        if (version > -1) {
            return version;
        }
        if (!isApplicationOnboardedVersionZero()) {
            return -1;
        }
        sharedPreferences.edit().putInt("pref_key_app_onboarding_version", 0).apply();
        return 0;
    }

    private static boolean isApplicationOnboardedVersionZero() {
        return new PblPreferences(PebbleApplication.getAppContext()).getBooleanData(PrefKey.ONBOARDING_COMPLETED, false);
    }

    private static SharedPreferences getInstance() {
        return PebbleApplication.getAppContext().getSharedPreferences("ONBOARDING_PREFERENCE", 4);
    }
}
